package com.gobygang.client;

import com.gobygang.client.Authenication.AuthStatus;
import com.gobygang.client.Authenication.Provider;
import com.gobygang.client.Authenication.Status;
import com.gobygang.client.GobygangHandler.Success;
import com.gobygang.client.Session.CreateJoinMode;
import com.gobygang.client.dialog.ProcessingDialog;
import com.gobygang.client.facebook.FacebookApi;
import com.gobygang.client.facebook.FacebookFactory;
import com.gobygang.client.facebook.GetUserDetailsCallback;
import com.gobygang.client.facebook.ThenGetUserDetails;
import com.gobygang.client.map.MapView;
import com.gobygang.client.map.NavigatorManager;
import com.gobygang.client.map.SearchView;
import com.gobygang.client.map.SearchView.TextBoxType;
import com.gobygang.client.ui.ButtonType;
import com.gobygang.client.uibinder.Alert;
import com.gobygang.client.uibinder.SearchAndCreate;
import com.gobygang.client.uibinder.TaxiGangHome;
import com.gobygang.shared.ChitInfo;
import com.gobygang.shared.RouteInfo;
import com.gobygang.shared.TaxiGangInfo;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.HasClickHandlers;
import com.google.gwt.user.client.Command;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.SuggestBox;
import com.google.gwt.user.client.ui.SuggestionEvent;
import com.google.gwt.user.client.ui.SuggestionHandler;


public class GobygangPresenter {

	private MapView mapView;
	private SearchView searchView;

	public void setMapView(MapView mapView){
		this.mapView = mapView;
		this.searchView = mapView.getSearchView();
		bindDisplay();

	}
	private static GobygangPresenter instance;

	public static GobygangPresenter getInstance(){
		if (instance==null){
			instance = new GobygangPresenter();
		}
		return instance;
	}


	private void bindDisplay(){

		for (final TextBoxType t : TextBoxType.values()){

			SuggestBox suggestBox =  searchView.getSuggestBox(t);

			suggestBox.addEventHandler(new SuggestionHandler(){

				@Override
				public void onSuggestionSelected(SuggestionEvent event) {
					fireOK(t);
				}

			});

		}



		searchView.getOKTimeButton().addClickHandler(new ClickHandler() {

			@Override
			public void onClick(ClickEvent event) {
				searchView.updateDepartureTime();

				searchView.setMode(SearchView.SearchDisplayMode.SEARCH_CREATE);
			}
		});



		//search & create

		searchView.getButton(ButtonType.Create).addClickHandler(new ClickHandler() {
			public void onClick(ClickEvent event) {

				create();
			}

		});

		searchView.getButton(ButtonType.Join).addClickHandler(new ClickHandler() {
			public void onClick(ClickEvent event) {

				join();
			}

		});


		searchView.getButton(ButtonType.Search).addClickHandler(new ClickHandler() {
			public void onClick(ClickEvent event) {
				//Log.info("SEARCH");
				if (checkStart() != null && checkDestination()!= null){
					searchView.updateDepartureTime();
					GobygangHandler.getInstance().searchForTaxiGangs();
					ProcessingDialog.show(Text.t.search());

				}
			}
		});


	}

	public void myTaxiGang(boolean showLoginOnLoggedOut){
		//Log.info("MYTAXIGANG:"+showLoginOnLoggedOut);
		//GobygangHandler.getInstance().getTaxiCompanies(Session.getInstance().getPostalCode());
		if (Authenication.getInstance().getAuthStatus()==AuthStatus.NotLoggedIn){
			login(CreateJoinMode.MYTAXIGANG,showLoginOnLoggedOut);
		} else {
			GobygangHandler.getInstance().searchForMyTaxiGangs(Success.NONE,null);
		}

	}

	public void create(){
		//Log.info("CREATE");
		//GobygangHandler.getInstance().getTaxiCompanies(Session.getInstance().getPostalCode());
		//Log.debug("auth status="+Authenication.getInstance().getAuthStatus());
		if (Authenication.getInstance().getAuthStatus()==AuthStatus.NotLoggedIn){
			mapView.setPanelToShowOnLogin(PanelType.MOBILENUMBER);
			login(CreateJoinMode.CREATE,true);
		} else {
			//myTaxiGangsWidget.getHideable().show();
			Session session = Session.getInstance();
			searchView.updateDepartureTime();

			String start = searchView.getTextBoxText(TextBoxType.START).getText().trim();				
			String destination = searchView.getTextBoxText(TextBoxType.DESTINATION).getText().trim();				

			TaxiGangInfo info = session.getSearchTaxiGangInfo();
			info.setStart(start);
			info.setDestination(destination);

			session.getSearchTaxiGangInfo().setStart(start);
			Session.getInstance().setCreateJoin(CreateJoinMode.CREATE);
			NavigatorManager.setUpForCreation(info,(SearchAndCreate)searchView,mapView);

		}

	}


	public void createWithWait(ChitInfo chit){
		ProcessingDialog.show(Text.t.processing());
		GobygangHandler.getInstance().createTaxiGang(chit);
	}
	public void joinWithWait(ChitInfo chit){
		ProcessingDialog.show(Text.t.processing());
		GobygangHandler.getInstance().joinTaxiGang(chit);
	}
	public void join(){
		//cancel invitation mode
		Session.getInstance().setRef(null);
		Session.getInstance().setCreateJoin(CreateJoinMode.JOIN);
		//Log.info("JOIN");
		//Log.debug("auth status="+Authenication.getInstance().getAuthStatus());
		if (Authenication.getInstance().getAuthStatus()==AuthStatus.NotLoggedIn){
			Window.alert("not sure: GobygangPresenter");
//			if (TaxigangMode.TAXIGANG == Session.getInstance().getMode()){
//				mapView.setPanelToShowOnLogin(PanelType.MOBILENUMBER);
//			}else{
//				mapView.setPanelToShowOnLogin(PanelType.SUGGESTION);
//			}
			login(CreateJoinMode.JOIN,true);
		} else {
			//show Mobilnummer window
			mapView.show(PanelType.MOBILENUMBER);
		}

	}

	public void login(CreateJoinMode mode,boolean showLoginOnLoggedOut) {
		ThenGetUserDetails thenGetUserDetails = null;
		switch (mode){
		case CREATE:
			thenGetUserDetails = new ThenGetUserDetails();
			break;
		case JOIN:
			thenGetUserDetails = new ThenGetUserDetails();
			break;
		case MYTAXIGANG:
			thenGetUserDetails = new ThenGetUserDetails();
			break;
		case LOGIN:
			FacebookApi.fbLogin();
			break;

		}
		if (mode != CreateJoinMode.LOGIN){
			final GetUserDetailsCallback getUserDetailsCallback =  new GetUserDetailsCallback(thenGetUserDetails,showLoginOnLoggedOut);
			Command command = new Command(){
				@Override
				public void execute(){
					FacebookApi.waitForAPI(getUserDetailsCallback);
				}
			};
			FacebookFactory.createFBConnection(null,command);
		}
	}

	public void fireOK(TextBoxType textBoxType) {
		switch (textBoxType){
		case START:

			String start = checkStart();
			if (start !=null){
				//				searchView.getTextBoxText(TextBoxType.START).setText("");
				//Log.info("updateStart="+start);
				Session.getInstance().getSearchTaxiGangInfo().setStart(start);				
				enterStart(Session.getInstance().getSearchTaxiGangInfo());
				searchView.setMode(SearchView.SearchDisplayMode.DESTINATION);

			}
			break;
		case DESTINATION:
			String destination = searchView.getTextBoxText(TextBoxType.DESTINATION).getText();
			//Log.info("updateDestination="+destination);
			Session.getInstance().getSearchTaxiGangInfo().setDestination(destination);
			enterDestination(Session.getInstance().getSearchTaxiGangInfo());
			searchView.setMode(SearchView.SearchDisplayMode.SEARCH_CREATE);

			break;
		}
	}

	private String checkAddress(TextBoxType textBoxType, String enterText){
		String address = searchView.getTextBoxText(textBoxType).getText();
		//Log.info("checkAddress="+address);
		if (address != null && address.trim().length() > 0){
			return address;
		}else {
			Window.alert(enterText);
			return null;
		}

	}
	private String checkStart(){
		return checkAddress(TextBoxType.START, Text.t.enterTheAddressTobegin());
	}
	private String checkDestination(){
		return checkAddress(TextBoxType.DESTINATION, Text.t.enterTheAddressToend());
	}


	public void enterStart(TaxiGangInfo taxiGangInfo){
		//Log.info("enterStart="+taxiGangInfo.getStart());
		if (mapView != null){
			mapView.createStartMarker(taxiGangInfo.getStart(),false);
		}

	}

	public void enterDestination(TaxiGangInfo taxiGangInfo){

		//Log.info("enterDest="+taxiGangInfo.getDestination());
		if (mapView != null){
			mapView.createDestinationMarker(taxiGangInfo.getDestination(),true);		
		}
	}


	public void displayMessages(){

		mapView.show(PanelType.MESSAGES);
	}

	public void showSuccess(GobygangHandler.Success success){
		switch (success){
		case NONE:
			break;

		case UPDATE:
			break;

		case JOIN:
			mapView.show(PanelType.CONGRATULATIONS_JOIN);
			//congratulationsJoinDia//Log.getHideable().show();
			break;

		case CREATE:
			mapView.show(PanelType.CONGRATULATIONS_CREATE);
		}

	}


	public void resetSuggestions(){
		Window.alert("TODO:resetSuggestions");

		//		if (
		//				Session.getInstance().getUserAgent()==UserAgent.PC ||
		//				Session.getInstance().getUserAgent()==UserAgent.PC_WEBKIT ||
		//				Session.getInstance().getUserAgent()==UserAgent.FB_WEBKIT ||
		//				Session.getInstance().getUserAgent()==UserAgent.FB
		//		){
		//			suggestionView.getHideable().hide();
		//		}
		//		mapView.resetSuggestion();

	}

	public void displayTaxiGangsList(){
		Session session = Session.getInstance();
		TaxiGangInfo[] taxigangInfoList = session.getTaxiGangSearchResultList();
		if (taxigangInfoList == null || taxigangInfoList.length == 0){
			mapView.show(PanelType.SORRY);

			//microNoTaxiGangsWidget.getHideable().show();			
		}else{
			Session.getInstance().setCurrentSuggestionIndex(0);
			mapView.show(PanelType.SUGGESTION);

			//			suggestionView.setButtonMode(ButtonMode.LIST_TAXIGANGS);
			//			session.setCurrentSuggestionIndex(0);
			//			suggestionView.showSuggestionInText(taxigangInfoList[0]);
			//			mapView.showSuggestionInMap(taxigangInfoList[0]);
		}

	}

	public void displayPartner(RouteInfo partnerInfo){
		//TODO cleanup
		//		//Todo
		//		//if (partnerInfo == null){
		//		if (false){
		//			mapView.show(PanelType.SORRY);
		//		}else{
		//			mapView.show(PanelType.SEARCH);
		//			mapView.createStartMarker("Westendstr. 80", "Munich", true);
		//
		//			Geolocator geolocation = new Geolocator();
		//			geolocation.runGeolocation(mapView);
		//
		//			//			suggestionView.setButtonMode(ButtonMode.LIST_TAXIGANGS);
		//			//			session.setCurrentSuggestionIndex(0);
		//			//			suggestionView.showSuggestionInText(taxigangInfoList[0]);
		//			//			mapView.showSuggestionInMap(taxigangInfoList[0]);
		//		}

	}

	//	public void updateTaxiCompanies(String postalCode, TaxiCompanyInfo[] listtaxiCompany) {
	//		mapView.setTaxiCompanyList(postalCode, listtaxiCompany);
	//
	//	}

	public void authenticationComplete(boolean showLoginOnLoggedout){
		////Log.info("TaxiGangPresenter:authenticationComplete");

		AuthStatus status = Authenication.getInstance().getAuthStatus();
		switch(status){
		case LoggedInGoogle:
			GobygangHandler.getInstance().searchForMyTaxiGangs(Success.NONE,null);
			break;

		case LoggedInFacebook:
			//Log.info("TaxiGangPresenter:authenticationComplete:LoggedInFacebook");
			mapView.setLoggedIn(Provider.Facebook);
			mapView.showLoginButton(false);
			break;

		case NotLoggedIn:
			//Log.info("TaxiGangPresenter:authenticationComplete:NotLoggedIn:"+showLoginOnLoggedout);

			mapView.showLoginButton(true);
			if (showLoginOnLoggedout){
				mapView.setLoggedOut("from TaxiGangPresenter:authenticationComplete");
			}


			break;

		case LoggedInTmp:
			GobygangHandler.getInstance().searchForMyTaxiGangs(Success.NONE,null);
			break;
		}

	}

	public void onFacebookLogin() {
		//Log.info("onFacebookLogin");
		Authenication.getInstance().setAuthStatus(Provider.Facebook, Status.LoggedIn);
		FacebookApi.waitUntilUserDetailsReady(new ThenGetUserDetails());
		mapView.setLoggedIn(Provider.Facebook);
	}

	public void onFacebookLogout() {
	}

	public void displayMyTaxiGangsList() {
		TaxiGangInfo[] myTaxiGangInfoList = Session.getInstance().getMyTaxiGangInfoList();
		//if (TaxiGangMain.getSession().getUserAgent() != UserAgent.IPHONE){
		if (myTaxiGangInfoList.length == 0){
			mapView.show(PanelType.SEARCH);
			Alert.alert(null,"Taxigang",Text.t.youHaveNoActiveTaxiGangs(),false,"422px");

		} else {
			mapView.show(PanelType.MYTAXIGANGS);
		}

	}

	public void showCantLeave() {
		Window.alert("TODO:showCantLeave");

	}

	public static void initUser(){
		final GobygangRouteLoader loader = new GobygangRouteLoader();



		final TaxiGangHome taxiGangHome = new TaxiGangHome();
		loader.setTaxiGangHome(taxiGangHome);

		//			TaxiGangRoute mapView = new TaxiGangRoute();
		//			TaxiGangPresenter taxiGangPresenter = TaxiGangPresenter.getInstance();
		//			taxiGangPresenter.setMapView(mapView);

		HasClickHandlers showMeMoreButton = taxiGangHome.getShowMeMoreButton();

		showMeMoreButton.addClickHandler(new ClickHandler() {

			@Override
			public void onClick(ClickEvent event) {

				loader.execute();

			}
		});
		//RootPanel.get().add(mapView);
		RootPanel.get().add(taxiGangHome);

		Gobygang.hideLoading();


	}


}
